package com.tevintao.marketingsystem.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioFormat;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.tencent.mm.modelvoice.MediaRecorder;
import com.tevintao.marketingsystem.R;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.services.DeviceInfoManager;
import com.tevintao.marketingsystem.services.MockServices;
import com.tevintao.marketingsystem.services.RecordTest;
import com.tevintao.marketingsystem.services.TaskLogicService;
import com.tevintao.marketingsystem.tool.NetWorkTool;
import com.tevintao.marketingsystem.tool.PackageTool;
import com.tevintao.marketingsystem.tool.SystemPathTool;
import com.tevintao.marketingsystem.xposted.HookWindowManagerGlobal;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    public static final String TAG = MainActivity.class.getSimpleName();

    private Button mRegisterBtn;
    private Button mCreateBtn, mStart, mStop, mPlay, mPlayStop;
    private TextView mInfo;
    private ScrollView mScrollView;

    private android.os.Handler handler = new Handler();

    public static final int CURRENT_USE_ANDROID_OS_SDK = Build.VERSION.SDK_INT;//4.4.4

    private RequestQueue queue = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        queue = Volley.newRequestQueue(this);
        mCreateBtn = (Button) findViewById(R.id.act_main_create);
        Button mTestBtn = (Button) findViewById(R.id.act_main_test);

        mRegisterBtn = (Button) findViewById(R.id.act_main_register);
        mRegisterBtn.setOnClickListener(this);
        Button mImportContacts = (Button) findViewById(R.id.act_main_contacts_import);
        Button mSetGps = (Button) findViewById(R.id.act_main_set_gps);
//        if (mSetGps != null) {
//            mSetGps.setOnClickListener(this);
//        }

        int appVersion = PackageTool.getAppVersionCode(this, this.getPackageName());
        mSetGps.setText("版本 " + appVersion);

        Button mRestNet = (Button) findViewById(R.id.act_main_rest_net_env);
        if (mRestNet != null) {
            mRestNet.setOnClickListener(this);
        }

        if (mImportContacts != null) {
            mImportContacts.setOnClickListener(this);
        }
        mCreateBtn.setOnClickListener(this);
        if (mTestBtn != null) {
            mTestBtn.setOnClickListener(this);
        }


        mInfo = (TextView) findViewById(R.id.act_main_info);

        mScrollView = (ScrollView) findViewById(R.id.act_main_scroll_view);
        startService(new Intent(this, TaskLogicService.class));
//        boolean bindService = bindService(new Intent(TaskLogicService.ACTION_START_TASK_LOGIC_SERVICE), conn, BIND_AUTO_CREATE);
//        if (bindService) {
//            Toast.makeText(this, "bindService = " + bindService, Toast.LENGTH_LONG).show();
//        }


        Button mAccountList = (Button) findViewById(R.id.act_open_account_list);
        if (mAccountList != null) {
            mAccountList.setOnClickListener(this);
        }
        Button mAddAccount = (Button) findViewById(R.id.act_main_add_account);
        if (mAddAccount != null) {
            mAddAccount.setOnClickListener(this);
        }


        RadioGroup mRadioGroup = (RadioGroup) findViewById(R.id.act_main_radioGroup);
        if (mRadioGroup != null) {
            mRadioGroup.setOnCheckedChangeListener(this);
        }

//        LogManager.getInstance().logInfo("oncreate");
//        LogManager.getInstance().logInfo("Build.ID=" + Build.ID);
//        LogManager.getInstance().logInfo("Build.DISPLAY=" + Build.DISPLAY);
//        LogManager.getInstance().logInfo("Build.PRODUCT=" + Build.PRODUCT);
//        LogManager.getInstance().logInfo("Build.DEVICE=" + Build.DEVICE);
//        LogManager.getInstance().logInfo("Build.BOARD=" + Build.BOARD);
//
//        LogManager.getInstance().logInfo("Build.MANUFACTURER=" + Build.MANUFACTURER);
//        LogManager.getInstance().logInfo("Build.BRAND=" + Build.BRAND);
//        LogManager.getInstance().logInfo("Build.MODEL=" + Build.MODEL);
//        LogManager.getInstance().logInfo("Build.BOOTLOADER=" + Build.BOOTLOADER);
//        LogManager.getInstance().logInfo("Build.RADIO=" + Build.RADIO);
//        LogManager.getInstance().logInfo("Build.HARDWARE=" + Build.HARDWARE);
//        LogManager.getInstance().logInfo("Build.SERIAL=" + Build.SERIAL);
//        LogManager.getInstance().logInfo("Build.VERSION.CODENAME=" + Build.VERSION.CODENAME);
//        LogManager.getInstance().logInfo("Build.VERSION.INCREMENTAL=" + Build.VERSION.INCREMENTAL);
//        LogManager.getInstance().logInfo("Build.VERSION.RELEASE=" + Build.VERSION.RELEASE);
//        LogManager.getInstance().logInfo("Build.VERSION.SDK=" + Build.VERSION.SDK);
//        LogManager.getInstance().logInfo("Build.VERSION.SDK_INT=" + Build.VERSION.SDK_INT);


        new Thread(new Runnable() {
            @Override
            public void run() {
                if (SystemPathTool.exitFile(AccountManager.DEVICE_FILE)) {
                    LogManager.getInstance().logError("SystemPathTool.exitFile(AccountManager.DEVICE_FILE)");
                } else {
                    LogManager.getInstance().logError("SystemPathTool.exitFile(AccountManager.DEVICE_FILE)!!!!!");
                }
            }
        }).start();

        Button mSetting = (Button) findViewById(R.id.act_main_setting);
        if (mSetting != null) {
            mSetting.setOnClickListener(this);
        }


        registerReceiver(mUpdateAccount, new IntentFilter(ACTION_UPDATE_ACCOUNT));
        registerReceiver(broadcastReceiver, new IntentFilter(ACTION_UPDATE_MESSAGE));

        mStart = (Button) findViewById(R.id.act_main_decord);
        if (mStart != null) {
            mStart.setOnClickListener(this);
        }

        mStop = (Button) findViewById(R.id.act_main_play_decord);
        if (null != mStop) {
            mStop.setOnClickListener(this);
        }

        mPlay = (Button) findViewById(R.id.act_main_play_start);
        if (null != mPlay) {
            mPlay.setOnClickListener(this);
        }
        mPlayStop = (Button) findViewById(R.id.act_main_play_stop);
        if (null != mPlayStop) {
            mPlayStop.setOnClickListener(this);
        }

        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
                startReboot();
            }
        }, 3000);
    }


    private void startReboot() {
        PackageTool.launchAppFormPackage(this, "com.taotianwen.autoup.autoupdate");
        sendBroadcast(new Intent("com.tevintao.startAutoServer"));//启动自动更新服务

        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
//                sendBroadcast(new Intent("com.tevintao.receiver.autoreboot"));
            }
        }, 30 * 1000);
    }

//    private static final String[] PHONES_PROJECTION = new String[]{Phone.DISPLAY_NAME, Phone.NUMBER, Phone.CONTACT_ID};
//
//    /**
//     * 得到手机通讯录联系人信息
//     **/
//    private void getPhoneContacts() {
//        ContentResolver resolver = getContentResolver();
//
//        // 获取手机联系人
//        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
//
//        Class clazz = phoneCursor != null ? phoneCursor.getClass() : null;
//
//        while (clazz != null) {
//            LogManager.getInstance().logError("clazz = " + clazz.getName());
//            Method[] methods = clazz.getDeclaredMethods();
//            for (Method method : methods) {
//                LogManager.getInstance().logInfo("method = " + method);
//            }
//            Field[] fields = clazz.getDeclaredFields();
//            for (Field field : fields) {
//                LogManager.getInstance().logInfo("field = " + field + " Name = " + field.getName());
//                if ("mCursor".equals(field.getName())) {
//                    try {
//                        field.setAccessible(true);
//                        Object baseCursor = field.get(phoneCursor);
//                        LogManager.getInstance().logInfo("baseCursor = " + baseCursor);
//                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
//                        LogManager.getInstance().logInfo("baseCursor IllegalAccessException = " + e);
//                    }
//                }
//            }
//            clazz = clazz.getSuperclass();
//        }
//
//        if (phoneCursor != null) {
//            while (phoneCursor.moveToNext()) {
//
//                //得到手机号码
//                String phoneNumber = phoneCursor.getString(1);
//                //当手机号码为空的或者为空字段 跳过当前循环
//
//                //得到联系人名称
//                String contactName = phoneCursor.getString(0);
//
//                //得到联系人ID
//                Long contactid = phoneCursor.getLong(2);
//
//                LogManager.getInstance().logInfo("phoneNumber = " + phoneNumber + " contactName = " + contactName + " contactid = " + contactid);
//
//            }
//
//            phoneCursor.close();
//        }
//    }


    @Override
    protected void onResume() {
        super.onResume();
        new Thread(mGetDeviceName).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String msg = checkCanRunningEnvironment();
                if (!AccountManager.SUCCESS_TAG.equals(msg)) {
                    showToast(msg);
                }
            }
        }).start();

        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        }, 3000);

        if (TaskLogicService.mTaskRunning) {
            RadioButton radioButton = (RadioButton) findViewById(R.id.act_main_run);
            radioButton.setChecked(true);
        } else {
            RadioButton radioButton = (RadioButton) findViewById(R.id.act_main_stop);
            radioButton.setChecked(true);
        }
        WindowManager wm = this.getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        LogManager.getInstance().logInfo("width = " + width + " height = " + height);

        int width1 = wm.getDefaultDisplay().getWidth();
        int height1 = wm.getDefaultDisplay().getHeight();
        LogManager.getInstance().logInfo("width1 = " + width1 + " height1 = " + height1);

        DisplayMetrics metric = new DisplayMetrics();
        metric.widthPixels = 40;
        metric.heightPixels = 50;
        LogManager.getInstance().logInfo("metric.widthPixels  = " + metric.widthPixels + " metric.heightPixels = " + metric.heightPixels);

        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width2 = metric.widthPixels;     // 屏幕宽度（像素）
        int height2 = metric.heightPixels;   // 屏幕高度（像素）
        LogManager.getInstance().logInfo("width2 = " + width2 + " height2 = " + height2);


        metric = getResources().getDisplayMetrics();
        int width3 = metric.widthPixels;     // 屏幕宽度（像素）
        int height3 = metric.heightPixels;   // 屏幕高度（像素）
        LogManager.getInstance().logInfo("width3 = " + width3 + " height3 = " + height3);
        LogManager.getInstance().logInfo("getResources metric = " + metric);

        LogManager.getInstance().logInfo("Build.FINGERPRINT " + Build.FINGERPRINT);

        Class contextImpl = null;
        try {
            contextImpl = getClassLoader().loadClass("android.app.ContextImpl");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        LogManager.getInstance().logInfo("contextImpl = " + contextImpl);

        List<View> views = HookWindowManagerGlobal.getInstance().getViews();
        for (View v : views) {
            LogManager.getInstance().logError("v = " + v);
        }
//        ChatNewChatDB.getInstance().clearFriend();
//        if (MockServices.checkClient()) {
//            try {
//                MockServices.getClient().setMobileDataEnable(true);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
//        }
//
//        getWindow().getDecorView().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (MockServices.checkClient()) {
//                    try {
//                        MockServices.getClient().setMobileDataEnable(false);
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }, 5000);


//        playMp3();

//        if (MockServices.checkClient()) {
//            try {
//                MockServices.getClient().startRecoder();
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
//        }
//
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    MockServices.getClient().stopRecoder();
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
//            }
//        }, 10000);

//        ChatMessageBean bean = ChatMessageBean.getNewChat(MainActivity.this);
//        LogManager.getInstance().logInfo("bean=" + bean);
//        if (null != bean) {
//            boolean delete = ChatMessageBean.deleteChatMessage(this, bean.getId());
//            LogManager.getInstance().logInfo("delete = " + delete);
//        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LogManager.getInstance().logError("getGlobal()=" + getGlobal());

                List<View> gViews = pirntView();
                for (View vv : gViews) {
                    LogManager.getInstance().logError("vv=" + vv);
                }
            }
        }, 3000);


    }

    private static Object getGlobal() {
        Class<?> windowManager = null;
        try {
            windowManager = Class.forName("android.view.WindowManagerGlobal");
            Field instanceField = windowManager.getDeclaredField("sDefaultWindowManager");
            instanceField.setAccessible(true);
            Object instance = instanceField.get(null);
            return instance;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<View> pirntView() {
        Object global = getGlobal();
        if (null == global) {
            LogManager.getInstance().logError("HookWindowManagerGlobal getViews null == global");
        }
        Object mViews = null;
        try {
            Class globalClass = global.getClass();
            Field mViewsField = globalClass.getDeclaredField("mViews");
            mViewsField.setAccessible(true);
            mViews = mViewsField.get(global);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("HookWindowManagerGlobal  NoSuchFieldException mViews " + e.getMessage());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("HookWindowManagerGlobal  IllegalAccessException mViews " + e.getMessage());
        } catch (Exception e) {
            LogManager.getInstance().logError("HookWindowManagerGlobal  Exception " + e.getMessage());
        }

        List<View> list;
        if (null != mViews) {
            try {
                list = (List<View>) mViews;
                return list;
            } catch (Exception e) {
                try {
                    View[] viewArray = (View[]) mViews;
                    list = new ArrayList();
                    for (View v : viewArray) {
                        list.add(v);
                    }
                    return list;
                } catch (Exception arrE) {
                    LogManager.getInstance().logError("HookWindowManagerGlobal mView is arraylist and is not array  = " + arrE.getMessage());
                }
            }
        }
        return null;
    }

    private void playMp3() {
        MediaPlayer mediaPlayer = new MediaPlayer();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.reset();//重置为初始状态
        }
        try {
            mediaPlayer.setDataSource("/mnt/sdcard/Music/fhcq.mp3");
            mediaPlayer.prepare();//缓冲
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("playMp3 IOException");
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    private String device_name;

    private Runnable mGetDeviceName = new Runnable() {
        @Override
        public void run() {
            if (!SystemPathTool.exitPath(AccountManager.MM_SD_CACHE_PATH)) {
                SystemPathTool.mkD(AccountManager.MM_SD_CACHE_PATH);
            }
            if (SystemPathTool.exitFile(ActSetDevice.device_name_file)) {
                device_name = SystemPathTool.getOutPutContent(ActSetDevice.device_name_file);
                if (TextUtils.isEmpty(device_name) || !TextUtils.isDigitsOnly(device_name)) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.this.startActivity(new Intent(MainActivity.this, ActSetDevice.class));
                        }
                    });
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.this.setTitle("设备名称为  " + device_name);
                        }
                    });
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.this.startActivity(new Intent(MainActivity.this, ActSetDevice.class));
                    }
                });
            }

        }
    };


    public static final String silkPath = "/mnt/sdcard/ms/fuck.silk";
    public static final String silkPathPcm = "/mnt/sdcard/ms/fuck.pcm";
    public static final int silkRate = 16000;
//    out480002
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.act_main_register:
                ConnectivityManager connManager = (ConnectivityManager) this
                        .getSystemService(CONNECTIVITY_SERVICE);
                // 获取代表联网状态的NetWorkInfo对象
                NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
                // 获取当前的网络连接是否可用
                if (null != networkInfo && !networkInfo.isAvailable()) {
                    showToast("通知 当前无可用的网络连接 ,至少保证存在手机网络连接");
                    return;
                }

                if (!hasSimCard()) {
                    showToast("请插入sim卡");
                    return;
                }

                @SuppressWarnings("deprecation") NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
                if (NetworkInfo.State.CONNECTED == state) {
                    showToast("注册请关闭wifi");
                    return;
                }

                setAirPlan(true);
                getWindow().getDecorView().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setAirPlan(false);
                        getWindow().getDecorView().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                sendBroadcast(new Intent(TaskLogicService.ACTION_TEST_TASK));
                            }
                        }, 5000);
                    }
                }, 5000);
                break;
            case R.id.act_main_rest_net_env:
                if (!checkEnvironment()) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String local = DeviceInfoManager.getInstance().resetNet();
                        LogManager.getInstance().logInfo(local);
                        showToast("重置网络 = " + local);
                        if (AccountManager.SUCCESS_TAG.equals(local)) {
                            showToast("重置网络成功");
                        } else {
                            showToast(local);
                        }
                    }
                }).start();
                break;
            case R.id.act_main_create:
                new AlertDialog.Builder(this).setTitle("确认创建环境吗？创建后之前的目录全部会删除.")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        final boolean create = AccountManager.getInstance(MainActivity.this).createContext();
                                        mCreateBtn.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, create ? " 创建环境成功" : "创建环境失败", Toast.LENGTH_LONG).show();
                                            }
                                        });
                                    }
                                }).start();
                            }
                        }).setNegativeButton("返回", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
                break;
            case R.id.act_main_test:
                sendBroadcast(new Intent(TaskLogicService.ACTION_TEST_TASK));
//                sendBroadcast(new Intent(TaskLogicService.ACTION_KEY_REPORT_FRIEND_ICON));
                break;
            case R.id.act_open_account_list:
                startActivity(new Intent(this, ActLocalAccount.class));
                break;
            case R.id.act_main_contacts_import:
                startActivity(new Intent(this, ActContactsImport.class));
                break;
            case R.id.act_main_set_gps:
                startActivity(new Intent(this, ActSetGps.class));
                break;

            case R.id.act_main_add_account:
//                addAccount();
                startActivity(new Intent(this, ActAddAccount.class));
                break;
            case R.id.act_main_setting:
                startActivity(new Intent(this, ActSetting.class));
                break;
            case R.id.act_main_decord:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        boolean decordState = MediaRecorder.getWxCoder(silkPath, silkPathPcm);
                        LogManager.getInstance().logError("decordState = " + decordState + " silkPath = " + silkPath);
                    }
                }).start();
//                setAirPlan(true);
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
////                        RecordTest.getInstance().selfRecord();
//
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                RecordTest.getInstance().selfPlay("/mnt/sdcard/ms/fhcq.pcm", 14700, AudioFormat.CHANNEL_OUT_STEREO);
//                            }
//                        }).start();
//                    }
//                }).start();
                break;
            case R.id.act_main_play_decord:
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
//                                RecordTest.getInstance().selfPlay(silkPathPcm, silkRate, AudioFormat.CHANNEL_OUT_STEREO);
                                RecordTest.getInstance().selfPlay(MediaRecorder.lastDecoderPath, silkRate, AudioFormat.CHANNEL_OUT_STEREO);
                                LogManager.getInstance().logError("AudioFormat.CHANNEL_OUT_STEREO = " + AudioFormat.CHANNEL_OUT_STEREO);
                                LogManager.getInstance().logError("AudioFormat.CHANNEL_CONFIGURATION_MONO = " + AudioFormat.CHANNEL_CONFIGURATION_MONO);
                            }
                        }).start();
                    }
                }).start();
                break;
            case R.id.act_main_play_start:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        RecordTest.getInstance().selfPlay(silkPathPcm, 16000, AudioFormat.CHANNEL_CONFIGURATION_MONO);
                    }
                }).start();
                break;
            case R.id.act_main_play_stop:
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
////                        RecordTest.getInstance().stopPlay();
////                        new VoiceDecoder().decode("/mnt/sdcard/ms/fhcq.mp3", "/mnt/sdcard/ms/fhcq.pcm");
//                        long start = System.currentTimeMillis();
//                        LogManager.getInstance().logInfo("解码用时 = start = " + start);
//                        try {
//                            boolean decoder = MediaRecorder.getWxCoder("/mnt/sdcard/ms/1.silk", "/mnt/sdcard/ms/2.pcm");
//                            LogManager.getInstance().logInfo(" decoder = " + decoder);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            LogManager.getInstance().logInfo(e.toString());
//                        }
//                        long end = System.currentTimeMillis();
//                        LogManager.getInstance().logInfo("解码用时 = end = " + end);
//                        LogManager.getInstance().logInfo("解码用时 = " + (end - start));
//                    }
//                }).start();
//                sendBroadcast(new Intent(WxTaskManger.ACTION_TEST_SILK));
//                boolean updateChatTime = LastUpdateDB.updateChatLastTime(this, "ccc", System.currentTimeMillis());
//                LogManager.getInstance().logInfo("updateChatTime = " + updateChatTime);
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        String result = UploadFileTool.uploadFile("http://192.168.1.100:8000/chat/updateFile?pm1=1&pm2=2", "/mnt/sdcard/ms/device_name");
//                        LogManager.getInstance().logInfo("返回数据 " + result);
//                    }
//                }).start();

                File rootFile = new File("/mnt/sdcard/tencent/micromsg/");
                File[] accountFiles = rootFile.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return pathname.getName().length() == "4bd870110c1017a763c0f412b9dd3e2d".length();
                    }
                });


                String path = "THUMBNAIL_DIRPATH://th_fba359af70fb7927e525b5df4a27b5de";
                String dir = path.substring(23, 25);
                String dir2 = path.substring(25, 27);
                LogManager.getInstance().logInfo("dir1 = " + dir + " dir2 = " + dir2);

                for (File checkFile : accountFiles) {
                    String checkPath = "/mnt/sdcard/tencent/micromsg/" + checkFile.getName() + "/image2/" + dir + "/" + dir2 + "/" + path.substring(20);
                    LogManager.getInstance().logInfo("checkFile.getName() = " + checkFile.getName() + " checkPath = " + checkPath);
                    if (new File(checkPath).exists()) {
                        LogManager.getInstance().logInfo("文件位置 " + checkPath);
                    }
                }
//                String realPath = "/mnt/sdcard/tencent/micromsg/" + dir + "/" + dir2 + "/" + path.substring(23);
//                File ff = new File(realPath);
//                LogManager.getInstance().logInfo("realPath =  " + realPath + " exists = " + ff.exists());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        long l1 = System.currentTimeMillis();
                        String realPath = getVideoPath("13110720121687d955470090");
                        long l2 = System.currentTimeMillis();
                        LogManager.getInstance().logInfo("找到路劲 " + realPath + " 用了 " + (l2 - l1) + " 毫秒");
                    }
                }).start();
                break;

        }
    }


    public String getVideoPath(String fileName) {
        File rootFile = new File("/mnt/sdcard/tencent/micromsg/");
        File[] accountFiles = rootFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().length() == "4bd870110c1017a763c0f412b9dd3e2d".length();
            }
        });
        String realName = fileName + ".jpg";

        for (File checkFile : accountFiles) {
            String checkPath = "/mnt/sdcard/tencent/micromsg/" + checkFile.getName() + "/video/" + realName;
            if (new File(checkPath).exists()) {
                LogManager.getInstance().logInfo("找到文件 " + checkPath);
                return checkPath;
            }
        }
        return null;
    }


    private void setAirPlan(boolean state) {
        if (MockServices.checkClient()) {
            try {
                MockServices.getClient().setMobileDataEnable(state);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        try {
            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            intent.putExtra("state", state);
            sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
            LogManager.getInstance().logError("setAirPlan Exception");
        }
    }

    /**
     * 程序启动，即可检查当前当人环境，并给出提示。
     * 显示在信息栏中
     */
    private String checkCanRunningEnvironment() {
        String tag = AccountManager.getInstance(this).checkContextTag();
        if (!AccountManager.SUCCESS_TAG.equals(tag)) {
            setMessage("初始化环境存在问题 " + tag);
            showToast(tag);
            return tag;
        } else {
            LogManager.getInstance().logInfo("帐号环境没问题");
        }

        if (!MockServices.checkClient()) {
            showToast("Xposed 错误");
            setMessage("Xposed错误");
            return "Xposed 错误";
        } else {
            LogManager.getInstance().logInfo("Xposed 正常");
        }

        if (NetWorkTool.getAirplaneMode(this)) {
            showToast("飞行模式");
            return AccountManager.SUCCESS_TAG;
        }

        if (!DeviceInfoManager.getInstance().isSameNet()) {
            showToast("当前流量卡和本地设备信息不属于同一网络 ,暂停运行，请从新设置网络环境");
            setMessage("当前流量卡和本地设备信息不属于同一网络 ,暂停运行，请从新设置网络环境");
            return "当前流量卡和本地设备信息不属于同一网络";
        } else {
            LogManager.getInstance().logInfo("网络没有改变");
        }


        if (!SystemPathTool.exitFile(AccountManager.LOCAL_DEVICE_INFO)) {
            showToast("设备基础信息不存在");
            setMessage("设备基础信息不存在");
            return "设备基础信息不存在";
        } else {
            LogManager.getInstance().logInfo("设备基础信息存在");
        }
        return AccountManager.SUCCESS_TAG;
    }

    private void showToast(final String msg) {
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }


    public boolean hasSimCard() {
        TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false; // 没有SIM卡
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
        }
        return result;
    }

    private boolean checkEnvironment() {
        ConnectivityManager connManager = (ConnectivityManager) this
                .getSystemService(CONNECTIVITY_SERVICE);
        // 获取代表联网状态的NetWorkInfo对象
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        // 获取当前的网络连接是否可用
        if (null != networkInfo && !networkInfo.isAvailable()) {
            showToast("通知 当前无可用的网络连接 ,至少保证存在手机网络连接");
            return false;
        }

        if (!hasSimCard()) {
            setMessage("请插入sim卡");
            return false;
        }

        @SuppressWarnings("deprecation") NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (NetworkInfo.State.CONNECTED != state) {
            setMessage("请打开wifi");
            startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
            return false;
        }

        return true;
    }

    private void setMessage(final String msg) {
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                String sb = mInfo.getText().toString() +
                        "\n" +
                        msg;
                mInfo.setText(sb);
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

    }


    public static final String ACTION_UPDATE_MESSAGE = "ACTION_UPDATE_MESSAGE";
    public static final String KEY_UPDATE_MESSAGE = "KEY_UPDATE_MESSAGE";
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                LogManager.getInstance().logInfo("broadcastReceiver TextUtils.isEmpty(action)");
            }
            LogManager.getInstance().logInfo("broadcastReceiver action = " + action);
            if (ACTION_UPDATE_MESSAGE.equals(action)) {
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    String message = bundle.getString(KEY_UPDATE_MESSAGE);
                    if (!TextUtils.isEmpty(message)) {
                        setMessage(message);
                    }
                }
            }
        }
    };

    public static void messageChange(Context context, String message) {
        if (null == context) {
            return;
        }
        Intent intent = new Intent(ACTION_UPDATE_MESSAGE);
        Bundle bundle = new Bundle();
        bundle.putString(KEY_UPDATE_MESSAGE, message);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.act_main_run) {
            Toast.makeText(this, "运行状态", Toast.LENGTH_SHORT).show();
            TaskLogicService.mTaskRunning = true;
        } else if (checkedId == R.id.act_main_stop) {
            Toast.makeText(this, "停止状态", Toast.LENGTH_SHORT).show();
            TaskLogicService.mTaskRunning = false;
        }
    }

    public static final String ACTION_UPDATE_ACCOUNT = "ACTION_UPDATE_ACCOUNT";
    public static final String KEY_UPDATE_ACCOUNT = "KEY_UPDATE_ACCOUNT";

    private BroadcastReceiver mUpdateAccount = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            if (null != extras) {
                String account = extras.getString(KEY_UPDATE_ACCOUNT);
                if (!TextUtils.isEmpty(account)) {
                    MainActivity.this.setTitle("设备 " + device_name + " 帐号" + account);
                }
            }
        }
    };

}
